#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <unistd.h>
 
#include <stdio.h>
#include <string.h>
 
int main(int argc,char *argv[]){
        int sockfd = -1; 
        struct sockaddr_in servaddr;
        int ret = 0;
 
        /*为了后续的UDP传输创建一个引擎对象，并获得该引擎对象的描述符*/
        sockfd = socket(AF_INET,SOCK_DGRAM,0);
    
        /*填写服务端的IP和端口号*/
        bzero(&servaddr,sizeof(servaddr));
        servaddr.sin_family = AF_INET;
        servaddr.sin_port = htons(8888);
        inet_aton("192.168.247.255",&servaddr.sin_addr);
 
        /*为服务端UDP socket引擎对象指定IP地址和端口号*/
        ret = bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
        if(ret){
                printf("In Server,bind failed\n");
                close(sockfd);
                sockfd = -1; 
                return 1;
        }

        /*接收广播数据*/
        while(1){
                char buf[10] = "";
                struct sockaddr_in cliaddr;
                struct sockaddr_in servaddr;
                socklen_t socklen = sizeof(cliaddr);
 
                recvfrom(sockfd,buf,10,0,(struct sockaddr *)&cliaddr,&socklen);

                if(!strcmp(buf,"smart")){
                        printf("device connect success\n");
                        printf("client port = %d\n",cliaddr.sin_port);
                        printf("client ip = %s\n",inet_ntoa(cliaddr.sin_addr));

                        sendto(sockfd,"yes",10,0,(struct sockaddr *)&cliaddr,socklen);
                }
                else printf("not my device\n");
        }

        /*无需继续接收广播数据时，及时关闭描述符*/
        close(sockfd);
        sockfd = -1; 
        return 0;
}